using Arcane.Source.Client;
using Arcane.Source.Combat;
using Godot;

namespace Arcane.Source.Data
{
    public class RuneSpellData
    {
        public Texture2D rune;
        public string description;
        public Expression[] exprs;

        public RuneSpellData(StringName name, Resource tres)
        {
            rune = tres.Get(StringNames.RUNE).As<Texture2D>();
            description = tres.Get(StringNames.DESCRIPTION).AsString();
            var src = tres.Get(StringNames.EXPR).AsString();
            if (src.Length <= 0) return;

            var lines = src.Split('\n');

            // GD.Print(name, ":", lines.Length);
            exprs = new Expression[lines.Length];
            for (int i = 0; i < lines.Length; i++)
            {
                exprs[i] = new Expression();

                var err = exprs[i].Parse(lines[i], ["col", "row"]);
                if (err != Error.Ok)
                {
                    GD.PrintErr($"{name} {err}");
                    exprs[i] = null;
                }
            }
        }

        public void Apply(Entity host, int col, int row)
        {
            if (exprs != null)
            {
                using var api = new EntityApi(host);
                for (int i = 0; i < exprs.Length; i++)
                {
                    if (exprs[i] == null) continue;
                    exprs[i].Execute([col, row], api);
                }
            }
            else
            {
                host.Attack(host.GetTarget(1), DamageType.Magical, 100);
            }
        }
    }
}